<?php

	$xml = simplexml_load_file('php://input');

	//XML Parse GoogleFeedSearch
	foreach( $xml->attributes( ) as $attr)
	{
		$AttrArray[] = $attr;
	}
	$Keyword = $AttrArray[0];
	//$api = 'http://www.google.com/reader/api/0/feed-finder?q='.$Keyword.'&num=20';
	//$api = 'https://news.google.com/news/feeds?q='.$Keyword.'&output=rss&&num=20';
	$api = 'https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q='.$Keyword;
	
	
    // Make an API request and create the cache file
	$response = get_curl($api);
	
	if (count(json_decode($response)->responseData->entries)!=0) {
		echo '<GoogleFeedResult>';
		
		foreach (json_decode($response)->responseData->entries as $object)
		{
			$url = $object->url;
			$title = $object->title;
			$content = $object->contentSnippet;
			
			//Check URL is feed.
			$url_Check = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=".$url."";
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url_Check);
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);	

			$body = curl_exec($ch);

			if (curl_errno($ch))
			{
				echo "ErrorCode:".curl_errno($ch);
				echo "ErrorMsg:".curl_error($ch);
			}
			else {
				$json = json_decode($body);
		
				if( $json->responseStatus == 200 )
					echo '<Feed Title="'.XMLCharEncode(strip_tags($title)).'" Content="'.XMLCharEncode(strip_tags($content)).'" Link="'.XMLCharEncode($url).'" />';
			}
		}
		echo '</GoogleFeedResult>';
	}
	else
		echo '<Error Message="The requested Information was not found" Domain="Configuration"/>';
	
	//Added curl for faster response
	function get_curl($url){
		if(function_exists('curl_init')){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
			$output = curl_exec($ch);
			echo curl_error($ch);
			curl_close($ch);
			return $output;
		}
		else
			return file_get_contents($url);
	}
	
	function XMLCharEncode( $Subject )
	{
		$Serach  = array( "<", ">", "&", "'","\"" );
		$Replace = array( "&lt;","&gt;","&amp;","&apos;","&quot;");
		return str_replace($Serach, $Replace, $Subject);
	}

?>
